package mediaindex

import (
	"fmt"
	"github.com/goccy/go-json"
	"github.com/gogf/gf/errors/gerror"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"gitlab.local/DO-module/new-filemanage-module/src/core/sqlitedb"
	"gitlab.local/TerraMaster/tos-modules/database/sqlitemodel"
	"gitlab.local/golibrary/utils"
	"gorm.io/gorm"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

const (
	MediaConf      = "/etc/media.conf"
	MediaJsonConf  = "/etc/.ter_media.conf"
	Minidlnad      = "/etc/init.d/minidlnad"
	MediaRunning   = "/usr/local/media/scanning"
	MediaCompleted = "/usr/local/media/completed"
	falseRunning   = "/usr/local/media/.sk"
	falseCompleted = "/usr/local/media/.ck"
	LastIndex      = "/usr/local/media/lastindex"
	ThumbnailConf  = "/etc/.thumbnail_media.conf"
)

type MediaIndexList struct {
	Path   string `json:"path"`   //文件路径
	Photo  string `json:"photo"`  //是否索引图片
	Music  string `json:"music"`  //是否索引音乐
	Video  string `json:"video"`  //是否索引视频
	Text   string `json:"text"`   //是否文件索引
	Name   string `json:"name"`   //文件夹名
	L_name string `json:"l_name"` //所在卷
}

type FolderList struct {
	Name       string `json:"name"`
	Path       string `json:"path"`
	VolumeName string `json:"volume_name"`
}

type MediaIndex struct {
	//folderService folder.MediaIndex

	db    sqlitedb.Getter
	media *gorm.DB
}

type Thumbnail struct {
	EnableThumbnail int `json:"enable_thumbnail"`
	ConversionLevel int `json:"conversion_level"` // 生成缩略图的品质 0 一般品质 1 高品质
}

func New(db sqlitedb.Getter) *MediaIndex {
	mediax := &MediaIndex{
		//folderService: folderService,
		db: db,
	}
	_ = mediax.DefaultFolder()
	return mediax

}

func (mi *MediaIndex) start() (*gorm.DB, error) {
	var err error
	if mi.media == nil {
		mi.media, err = sqlitedb.MediaDB()
		if err != nil {
			return nil, gerror.Wrap(err, "connection mediadb failed")
		}
	}
	return mi.media, nil
}

func (mi *MediaIndex) DefaultFolder() error {
	//重装系统，设置媒体索引默认public索引目录
	// if !utils.Exists(MediaJsonConf) {
	// 	return mi.DefaultAddFolder()
	// }

	//若升级系统，media配置文件被初始化，则根据之前配置文件补齐media相关的配置目录
	list, err := GetMediaJsonList()
	if err != nil || len(list) == 0 {
		return nil
	}
	mediaConf, _ := os.ReadFile(MediaConf)
	for _, k := range list {
		if strings.Contains(string(mediaConf), k.Path) {
			continue
		}
		var photo, music, video, text string
		if k.Photo == "1" {
			photo = "P"
		}
		if k.Music == "1" {
			music = "A"
		}
		if k.Video == "1" {
			video = "V"
		}
		if k.Text == "1" {
			text = "T"
		}
		pav := photo + music + video + text
		if pav != "" {
			_ = WriteMediaConf("add", k.Path, pav)
		}
	}
	return nil
}

func (mi *MediaIndex) DefaultAddUserFolder() error {
	var userData []sqlitemodel.UserTable
	db := mi.db.DbGet()
	_ = db.Where("password not in ?", []string{"group", "adnet", "adgroup"}).Select("username").Find(&userData)
	for _, user := range userData {
		if user.Username == "guest" {
			continue
		}
		folderpath := filepath.Join("/home", user.Username)
		if !utils.Exists(folderpath) {
			continue
		}
		var mil MediaIndexList
		mil.Name = filepath.Base(folderpath)
		mil.Path = folderpath
		mil.L_name = "homes"
		mil.Music = "1"
		mil.Video = "1"
		mil.Photo = "1"
		mil.Text = "1"
		_, _ = AddMediaIndex(mil)
	}
	return nil
}

func (mi *MediaIndex) DefaultAddFolder() error {
	_ = mi.DefaultAddPublicFolder()
	_ = mi.DefaultAddUserFolder()
	//_ = mi.DefaultAddHomeFolder()
	return nil
}

func (mi *MediaIndex) DefaultAddPublicFolder() error {
	paths, err := filepath.Glob("/*/public")
	if err != nil {
		return err
	}
	path := "/Volume1/public"
	if len(paths) > 0 {
		path = paths[0]
	}
	var mil MediaIndexList
	mil.Name = filepath.Base(path)
	mil.Path = path
	mil.L_name = filepath.Base(filepath.Base(path))
	mil.Music = "1"
	mil.Video = "1"
	mil.Photo = "1"
	mil.Text = "1"
	_, _ = AddMediaIndex(mil)
	return nil
}

// WriteMediaConf 修改Mediaconf配置文件
// AddOrDel --"add","del","edit"
// path  -- "/Volume1/public"
// PAVT   -- p-photo ; a-music ; v-vedio ; T-TEXT
func WriteMediaConf(AddOrDel, path, PAV string) error {

	// 替换第一个homes
	path = strings.Replace(path, "/homes", "/home", 1)

	file, err := os.ReadFile(MediaConf)
	if err != nil {
		logrus.Warning("MediaConf", err)
	}
	lines := strings.Split(string(file), "\n")
	var content string
	regx, _ := regexp.Compile("^ *$")

	switch AddOrDel {
	case "add":
		dir := fmt.Sprintf("media_dir=%s,%s\n", PAV, path)
		content = string(file) + "\n" + dir
		if strings.Contains(string(file), dir) {
			content = string(file)
		}

	case "del":
		var line []string
		for _, k := range lines {
			if strings.Contains(k, "media_dir") && strings.Contains(k, path) {
				continue
			}

			if ok := regx.Match([]byte(k)); ok {
				continue
			}

			line = append(line, k)
		}
		content = strings.Join(line, "\n")
	case "edit":
		var line []string
		for _, k := range lines {
			if strings.Contains(k, "media_dir") && strings.Contains(k, path) {
				k = fmt.Sprintf("media_dir=%s,%s\n", PAV, path)
			}

			// 一行都是空格
			if ok := regx.Match([]byte(k)); ok {
				continue
			}

			line = append(line, k)
		}
		content = strings.Join(line, "\n")
	}
	_, err = utils.WriteFile(MediaConf, content)
	if err != nil {
		logrus.Warning("MediaConf1", err)
	}

	/*if strings.Contains(content, "media_dir") {
		AddMediaIndexExecShell()
	}*/
	return nil
}

// GetMediaJsonList 获取媒体索引目录列表
func GetMediaJsonList() (result []MediaIndexList, errResult error) {
	if !utils.Exists(MediaJsonConf) {
		errResult = nil
		return
	}
	body, err := os.ReadFile(MediaJsonConf)
	if err != nil || strings.TrimSpace(string(body)) == "" {
		errResult = errors.Wrap(err, "read config failed")
		return
	}
	var mediaList []MediaIndexList
	if err = json.Unmarshal(body, &mediaList); err != nil {
		errResult = errors.Wrap(err, "parse config failed")
		return
	}
	result = mediaList
	return
}
